<?php

namespace App\Http\Controllers;

use App\Models\DepositType;
use App\Models\ElectricFeeType;
use App\Models\ManageFeeType;
use App\Models\StaffPosition;
use App\Models\WaterFeeType;
use App\Models\HotWaterFeeType;
use Prettus\Validator\Contracts\ValidatorInterface;
use Prettus\Validator\Exceptions\ValidatorException;
use App\Http\Requests\DormTypeCreateRequest;
use App\Http\Requests\DormTypeUpdateRequest;
use App\Repositories\DormTypeRepository;
use App\Validators\DormTypeValidator;

/**
 * Class DormTypesController.
 *
 * @package namespace App\Http\Controllers;
 */
class DormTypesController extends Controller
{
    /**
     * @var DormTypeRepository
     */
    protected $repository;

    /**
     * @var DormTypeValidator
     */
    protected $validator;

    /**
     * DormTypesController constructor.
     *
     * @param DormTypeRepository $repository
     * @param DormTypeValidator $validator
     */
    public function __construct(DormTypeRepository $repository, DormTypeValidator $validator)
    {
        $this->repository = $repository;
        $this->validator  = $validator;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $this->repository->pushCriteria(app('Prettus\Repository\Criteria\RequestCriteria'));
        $dormTypes = $this->repository->with(['company', 'staffPosition', 'electricFeeType', 'waterFeeType', 'hotWaterFeeType', 'manageFeeType', 'depositTypes'])->all();

        \request()->flash();
        if (request()->wantsJson()) {

            return response()->json([
                'data' => $dormTypes,
            ]);
        }

        return view('dormTypes.index', compact('dormTypes'));
    }

    public function create()
    {
        $staffPositions = StaffPosition::all()->pluck('position', 'id');
        $electricFeeTypes = ElectricFeeType::all()->pluck('name', 'id')->toArray();
        $electricFeeTypes = array_unique($electricFeeTypes);
        $waterFeeTypes = WaterFeeType::all()->pluck('name', 'id');
        $hotWaterFeeTypes = HotWaterFeeType::all()->pluck('name', 'id');
        $manageFeeTypes = ManageFeeType::all()->pluck('name', 'id');
        $depositTypes = DepositType::all()->pluck('name', 'id');
        return view('dormTypes.create', compact('staffPositions', 'electricFeeTypes', 'waterFeeTypes', 'hotWaterFeeTypes', 'manageFeeTypes', 'depositTypes'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  DormTypeCreateRequest $request
     *
     * @return \Illuminate\Http\Response
     *
     * @throws \Prettus\Validator\Exceptions\ValidatorException
     */
    public function store(DormTypeCreateRequest $request)
    {
        try {

            $this->validator->with($request->all())->passesOrFail(ValidatorInterface::RULE_CREATE);

            $dormType = $this->repository->create($request->all());
            $dormType->depositTypes()->sync($request->get('deposit_type_ids'));

            $response = [
                'message' => 'DormType created.',
                'data'    => $dormType->toArray(),
            ];

            if ($request->wantsJson()) {

                return response()->json($response);
            }

            return redirect()->back()->with('message', $response['message']);
        } catch (ValidatorException $e) {
            if ($request->wantsJson()) {
                return response()->json([
                    'error'   => true,
                    'message' => $e->getMessageBag()
                ]);
            }

            return redirect()->back()->withErrors($e->getMessageBag())->withInput();
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $dormType = $this->repository->find($id);

        if (request()->wantsJson()) {

            return response()->json([
                'data' => $dormType,
            ]);
        }

        return view('dormTypes.show', compact('dormType'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $dormType = $this->repository->with('depositTypes')->find($id);
        $staffPositions = StaffPosition::all()->pluck('position', 'id');
        $electricFeeTypes = ElectricFeeType::all()->pluck('name', 'id');
        $waterFeeTypes = WaterFeeType::all()->pluck('name', 'id');
        $hotWaterFeeTypes = HotWaterFeeType::all()->pluck('name', 'id');
        $manageFeeTypes = ManageFeeType::all()->pluck('name', 'id');
        $depositTypes = DepositType::all()->pluck('name', 'id');
        return view('dormTypes.edit', compact('dormType', 'staffPositions', 'electricFeeTypes', 'waterFeeTypes', 'hotWaterFeeTypes', 'manageFeeTypes', 'depositTypes'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  DormTypeUpdateRequest $request
     * @param  string            $id
     *
     * @return Response
     *
     * @throws \Prettus\Validator\Exceptions\ValidatorException
     */
    public function update(DormTypeUpdateRequest $request, $id)
    {
        try {

            $this->validator->with($request->all())->passesOrFail(ValidatorInterface::RULE_UPDATE);

            $dormType = $this->repository->update($request->all(), $id);
            $dormType->depositTypes()->sync($request->get('deposit_type_ids'));

            $response = [
                'message' => 'DormType updated.',
                'data'    => $dormType->toArray(),
            ];

            if ($request->wantsJson()) {

                return response()->json($response);
            }

            return redirect()->back()->with('message', $response['message']);
        } catch (ValidatorException $e) {

            if ($request->wantsJson()) {

                return response()->json([
                    'error'   => true,
                    'message' => $e->getMessageBag()
                ]);
            }

            return redirect()->back()->withErrors($e->getMessageBag())->withInput();
        }
    }


    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if ($this->repository->find($id)->buildings->count()) {
            if (request()->wantsJson()) {

                return response()->json([
                    'error' => true,
                    'message' => '已经被引用，不能删除。',
                ]);
            }

            return redirect()->back()->withErrors('message', '已经被引用，不能删除。');
        } else {

            $deleted = $this->repository->delete($id);

            if (request()->wantsJson()) {

                return response()->json([
                    'message' => 'DormType deleted.',
                    'deleted' => $deleted,
                ]);
            }

            return redirect()->back()->with('message', 'DormType deleted.');
        }
    }
}
